package com.nx.platform.es.biz.esspider.handler;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.nx.platform.es.common.utils.MoreSplitters;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.common.utils.MoreFunctions;
import com.nx.platform.es.common.utils.MoreMaps;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by  on 2017/9/26.
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleIntFieldsMergerHandler extends AbstractSimpleHandler {

    private String[] fromFields;
    private String toField;
    private boolean filterZero;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        fromFields = MoreMaps.getStringArray(settings, "fromFields", MoreSplitters.COMMA);
        toField = MoreMaps.getString(settings, "toField");
        filterZero = MoreMaps.getBooleanValue(settings, "filterZero", true);
        Preconditions.checkArgument(fromFields != null && fromFields.length > 0, "fromFields null or empty");
        Preconditions.checkArgument(!Strings.isNullOrEmpty(toField), "toField null or empty");
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {
        items.values().forEach((Item item) -> {
            Map<String, Object> doc = item.getDoc();
            List<Integer> list = Stream.of(fromFields).map(doc::get)
                    .map(MoreFunctions::objectToInteger)
                    .filter(Objects::nonNull)
                    .filter(i -> !filterZero || i != 0)
                    .distinct().collect(Collectors.toList());
            doc.put(toField, list);
        });
    }

}
